package com.chenchen.subject.domain.serivice.impl;


import com.alibaba.fastjson.JSON;
import com.chenchen.subject.common.enums.IsDeletedFlagEnum;
import com.chenchen.subject.domain.convert.SubjectCategoryConverter;
import com.chenchen.subject.domain.entity.SubjectCategoryBo;
import com.chenchen.subject.domain.entity.SubjectLabelBo;
import com.chenchen.subject.domain.serivice.SubjectCategoryDomainService;
import com.chenchen.subject.domain.util.CacheUtil;
import com.chenchen.subject.infra.basic.entity.SubjectCategory;
import com.chenchen.subject.infra.basic.entity.SubjectLabel;
import com.chenchen.subject.infra.basic.entity.SubjectMapping;
import com.chenchen.subject.infra.basic.service.SubjectCategoryService;
import com.chenchen.subject.infra.basic.service.SubjectLabelService;
import com.chenchen.subject.infra.basic.service.SubjectMappingService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * ClassName SubjectCategoryDomainServiceImpl
 * description:
 *
 * @author 海问香
 * @createTime 2024/7/15 18:43
 */
@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;

    @Override
    public void add(SubjectCategoryBo subjectCategoryBo) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryBo.add.Bo:{}", JSON.toJSONString(subjectCategoryBo));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public List<SubjectCategoryBo> queryCategory(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBo> boList = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}", JSON.toJSONString(boList));
        }

        return boList;

    }

    @Override
    public Boolean update(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBo);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public List<SubjectCategoryBo> queryCategoryAndLabel(SubjectCategoryBo subjectCategoryBo) {
        Long id = subjectCategoryBo.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBo.getId();
        List<SubjectCategoryBo> subjectCategoryBOS = cacheUtil.getResult(cacheKey,
                SubjectCategoryBo.class, (key) -> getSubjectCategoryBos(id));
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBo> getSubjectCategoryBos(Long categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategoryAndLabel.subjectCategoryList:{}",
                    JSON.toJSONString(subjectCategoryList));
        }

        List<SubjectCategoryBo> categoryBoList = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
        //依次获取标签信息
        // 创建一个Map，用于存放SubjectLabelBo对象
        Map<Long, List<SubjectLabelBo>> map = new HashMap<>();
        // 将categoryBoList中的每一个元素转换为一个CompletableFuture对象，并将这些对象存放到一个List中
        List<CompletableFuture<Map<Long, List<SubjectLabelBo>>>> completableFutureList = categoryBoList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(category), labelThreadPool)).collect(Collectors.toList());
        // 遍历completableFutureList中的每一个元素，并获取其结果
        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBo>> resultMap = future.get();
                if (!CollectionUtils.isEmpty(resultMap)) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        // 遍历categoryBoList中的每一个元素，将map中对应的SubjectLabelBo对象设置到categoryBO中
        categoryBoList.forEach(categoryBO -> {
            if (!CollectionUtils.isEmpty(map.get(categoryBO.getId()))) {
                categoryBO.setLabelBoList(map.get(categoryBO.getId()));
            }
        });
        // 返回categoryBoList
        return categoryBoList;
    }

    private Map<Long, List<SubjectLabelBo>> getLabelBOList(SubjectCategoryBo category) {
        if (log.isInfoEnabled()) {
            log.info("getLabelBOList:{}", JSON.toJSONString(category));
        }
        Map<Long, List<SubjectLabelBo>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return null;
        }
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBo> labelBoList = new LinkedList<>();
        labelList.forEach(label -> {
            SubjectLabelBo subjectLabelBo = new SubjectLabelBo();
            subjectLabelBo.setId(label.getId());
            subjectLabelBo.setLabelName(label.getLabelName());
            subjectLabelBo.setCategoryId(label.getCategoryId());
            subjectLabelBo.setSortNum(label.getSortNum());
            labelBoList.add(subjectLabelBo);
        });
        labelMap.put(category.getId(), labelBoList);
        return labelMap;
    }
}
